import { defineStore } from 'pinia';
import type { FormComponentType } from '/#/form';
import { v4 as uuid } from 'uuid';
import { cloneDeep } from 'lodash-es';
import { leftComponents } from './data';

interface IFormConfig {
  layout?: 'inline' | 'horizontal' | 'vertical';
  labelWrap?: boolean;
  labelAlign?: 'left' | 'right';
  disabled?: boolean;
  colon?: boolean;
  name?: string;
  gutter?: number;
}

interface IComponentList<T> {
  title: string;
  list: FormComponentType<T>[];
}
interface IState {
  leftComponents: IComponentList<any>[];
  drawingList: FormComponentType<any>[];
  formConf: IFormConfig;
  activeComp: FormComponentType<any>;
  previewForm: FormComponentType<any>[];
}

export const useFormStore = defineStore({
  id: 'app-form',
  state: (): IState => ({
    leftComponents,
    drawingList: [],
    formConf: {
      layout: 'horizontal',
      labelWrap: false,
      labelAlign: 'left',
      disabled: true,
      colon: true,
      name: '',
      gutter: 24,
    },
    activeComp: {},
    previewForm: [],
  }),
  getters: {
    formState: (state) => {
      const form = {};
      state.previewForm.map((i) => {
        form[i.__config__?.name] = i.defaultValue;
      });
      return form;
    },
  },
  actions: {
    /**
     * 添加组件
     * @param comp
     */
    addComponent(comp) {
      const clone = cloneDeep({ ...comp, uuid: uuid() });
      clone.__config__.name = uuid();
      this.activeComp = clone;
      this.drawingList.push(clone);
    },
    /**
     * 拖拽复制组件
     * @param comp
     */
    cloneComponent(comp) {
      const clone = cloneDeep({ ...comp, uuid: uuid() });
      clone.__config__.name = uuid();
      this.activeComp = clone;
    },
    /**
     * 删除组件
     * @param index
     */
    delComponent(index) {
      this.drawingList.splice(index, 1);
    },
    /**
     * 复制组件
     * @param comp
     * @param index
     */
    copyComponent(comp, index) {
      const clone = cloneDeep({ ...comp, uuid: uuid() });
      clone.__config__.name = uuid();
      this.drawingList.splice(index + 1, 0, clone);
    },
  },
});
